package com.guli.cart.conf;

import com.alibaba.nacos.client.utils.StringUtils;
import com.guli.cart.vo.UserVo;
import com.guli.common.vo.MemberTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author WZH
 * @title: CartIntercepter
 * @projectName gulimall-java
 * @description:
 * @date 2022/1/19
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    @Autowired
    public static ThreadLocal<UserVo> threadLocal=new ThreadLocal<UserVo>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MemberTo member = (MemberTo) request.getSession().getAttribute("member");
        UserVo userVo = new UserVo();
        //session如果有登录用户就赋值id
        if (member!=null){
            userVo.setUserId(member.getId().toString());
        }
        //判断前端cookie有游客id就赋值
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("userKey".equals(cookie.getName())){
                userVo.setUserKey(cookie.getValue());
            }
        }
        //如果cookie无值就随机生成
        if (StringUtils.isEmpty(userVo.getUserKey())){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            userVo.setUserKey(uuid);
            userVo.setFlag(true);
        }
        threadLocal.set(userVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserVo userVo = threadLocal.get();
        //判断是新生成的游客id在该线程执行时并赋值给前台cookie
        if (userVo.getFlag()){
            Cookie userCookie = new Cookie("userKey", userVo.getUserKey());
            userCookie.setMaxAge(15*24*60*60);
            userCookie.setDomain("gulimall.com");
            response.addCookie(userCookie);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
